﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MutiCodecO.codeclib
{
    class Hex2Asii : ICodec
    {
        private int hexstr2int(String s)
        {
            if (s.Length > 2)
                return -1;
            int d = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] >= '0' && s[i] <= '9')
                    d += (i == 1 ? (s[i] - '0') : (s[i] - '0') * 16);
                else if (s[i] >= 'a' && s[i] <= 'f')
                    d += (i == 1 ? (s[i] - 'a' + 10) : (s[i] - 'a' + 10) * 16);
                else if (s[i] >= 'A' && s[i] <= 'F')
                    d += (i == 1 ? (s[i] - 'A' + 10) : (s[i] - 'A' + 10) * 16);
                else
                    return -1;
            }
            return d;
        }

        public String parse(String strInput)
        {
            String[] sa = strInput.Split(',');
            List<byte> bytesOutput = new List<byte>();
            for (int i = 0; i < sa.Length; i++)
            {
                int d = hexstr2int(sa[i]);
                if (d == -1)
                {
                    bytesOutput.Add((byte)',');
                    for (int j = 0; j < sa[i].Length; j++)
                        bytesOutput.Add((byte)sa[i][j]);
                }
                else
                    bytesOutput.Add((byte)d);
            }
            return Encoding.Default.GetString(bytesOutput.ToArray());
        }

        public String parse(String strInput, String prefix, String partion)
        {
            String s = parse(strInput);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                sb.Append(prefix);
                sb.Append(s[i]);
                if (i != s.Length - 1)
                    sb.Append(partion);
            }
            return sb.ToString();
        }
    }
}
